package com.zzk.lanouhn.myapplication1.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.zzk.lanouhn.myapplication1.R;
import com.zzk.lanouhn.myapplication1.adapters.RecyclerViewPopupAdapter;
import com.zzk.lanouhn.myapplication1.intefaces.NewsItemCliclListener;
import com.zzk.lanouhn.myapplication1.modles.NewsDetails;
import com.zzk.lanouhn.myapplication1.modles.Users;
import com.zzk.lanouhn.myapplication1.view.ScrollRecyclerView;

import java.io.IOException;
import java.text.SimpleDateFormat;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 资讯二级页面
 * Created by lanouhn on 16/8/27.
 */
public class AllNewsDetailsActivity extends Activity implements View.OnClickListener, NewsItemCliclListener {
    private NewsDetails details;//详情内容实体类
    private ImageView iv_authors_icon, iv_down, iv_up, iv_stand;
    private RadioButton iv_back, iv_comment, iv_share;
    private TextView tv_autograph, tv_authors_name, tv_title_details, tv_articles, tv_viewcount,tv_time;
    private String feedId;
    private WebView tv_contents_details;
    private Users user;
    private PopupWindow popup;
    private ScrollRecyclerView recycler;
    private RecyclerViewPopupAdapter adapter;
    private RelativeLayout rel_bg;
    private CheckBox iv_favorite;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_basenewsdetials);
        initView();
        initData();
        initEvent();
        getDataFromWeb();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        popup.dismiss();
    }

    private void initView() {

        iv_authors_icon = (ImageView) findViewById(R.id.iv_authors_icon_news_details);
        iv_down = (ImageView) findViewById(R.id.iv_down_news_details);
        iv_stand = (ImageView) findViewById(R.id.iv_stand_news_details);
        iv_up = (ImageView) findViewById(R.id.iv_up_news_details);
        tv_authors_name = (TextView) findViewById(R.id.tv_authors_name_news_details);
        tv_autograph = (TextView) findViewById(R.id.tv_autograph_news_details);
        tv_title_details = (TextView) findViewById(R.id.tv_title_news_details);
        tv_contents_details = (WebView) findViewById(R.id.tv_contents_news_details);
        iv_back = (RadioButton) findViewById(R.id.iv_news_details_back);
        iv_comment = (RadioButton) findViewById(R.id.iv_news_details_comments);
        iv_favorite = (CheckBox) findViewById(R.id.iv_news_details_favorite);
        iv_share = (RadioButton) findViewById(R.id.iv_news_details_share);
        View view1 = LayoutInflater.from(AllNewsDetailsActivity.this).inflate(R.layout.popupwindow_newsdetails, null);
        tv_articles = (TextView) view1.findViewById(R.id.article_amount_total);
        tv_viewcount = (TextView) view1.findViewById(R.id.viewcount_article_total);
        recycler = (ScrollRecyclerView) view1.findViewById(R.id.recycler_popup_details);
        popup = new PopupWindow(view1);
        rel_bg = (RelativeLayout) findViewById(R.id.rel_back);
        tv_time= (TextView) findViewById(R.id.tv_time_news_details);


    }

    private void initData() {
        Bundle bundle = this.getIntent().getExtras();
        feedId = bundle.getString("详情");
    }

    private void initEvent() {
        iv_authors_icon.setOnClickListener(this);
        tv_authors_name.setOnClickListener(this);
        iv_stand.setOnClickListener(this);
        tv_autograph.setOnClickListener(this);
        iv_down.setOnClickListener(this);
        iv_up.setOnClickListener(this);
        iv_back.setOnClickListener(this);
        iv_comment.setOnClickListener(this);
        iv_favorite.setOnClickListener(this);
        iv_share.setOnClickListener(this);

    }

    private void getDataFromWeb() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String url = "https://rong.36kr.com/api/mobi/news/" + feedId;
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(url)
                        .build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
                        final Gson gson = new Gson();
                        details = gson.fromJson(result, NewsDetails.class);
                        if (!"".equals(details.getData())) {
                            handler.sendEmptyMessage(1);
                        } else {
                            handler.sendEmptyMessage(0);
                        }
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                String authorUrl = "https://rong.36kr.com/api/mobi/news/" + feedId + "/author-region";
                                OkHttpClient clients = new OkHttpClient();
                                Request requests = new Request.Builder()
                                        .url(authorUrl)
                                        .build();

                                Call calls = clients.newCall(requests);
                                calls.enqueue(new Callback() {
                                    @Override
                                    public void onFailure(Call call, IOException e) {

                                    }

                                    @Override
                                    public void onResponse(Call call, Response response) throws IOException {
                                        String results = response.body().string();
                                        Gson gsons = new Gson();
                                        user = gsons.fromJson(results, Users.class);
                                        if (!"".equals(user.getData())) {
                                            handler.sendEmptyMessage(2);
                                        } else {
                                            handler.sendEmptyMessage(0);
                                        }
                                    }
                                });
                            }
                        }).start();
                    }
                });
            }
        }).start();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    Toast.makeText(AllNewsDetailsActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    long date=details.getData().getPublishTime();
                    SimpleDateFormat dateFormat=new SimpleDateFormat("MM-dd HH:mm");
                    String str = dateFormat.format(date);
                    tv_authors_name.setText(details.getData().getUser().getName());
                    tv_title_details.setText(details.getData().getTitle());
                    tv_time.setText(str);
                    tv_contents_details.getSettings().setDefaultTextEncodingName("UTF-8");
                    tv_contents_details.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
                    tv_contents_details.getSettings().setLoadWithOverviewMode(true);
                    tv_contents_details.loadData(details.getData().getContent(), "text/html; charset=UTF-8", null);
                    Picasso.with(AllNewsDetailsActivity.this).load(details.getData().getUser().getAvatar()).into(iv_authors_icon);
                    break;
                case 2:
                    tv_autograph.setText(user.getData().getBrief());
                    tv_articles.setText(String.valueOf(user.getData().getTotalCount()) + "篇");
                    int viewcount = user.getData().getTotalView() / 10000;
                    tv_viewcount.setText(String.valueOf(viewcount) + "万");
                    if (user.getData().getLatestArticle().size() > 0) {
                        adapter = new RecyclerViewPopupAdapter(AllNewsDetailsActivity.this, user);
                        adapter.setRecyclerViewPopupAdapter(AllNewsDetailsActivity.this);
                        recycler.setAdapter(adapter);
                        LinearLayoutManager manager = new LinearLayoutManager(AllNewsDetailsActivity.this);
                        manager.setOrientation(LinearLayoutManager.VERTICAL);
                        recycler.setLayoutManager(manager);
                    }
                    break;
                default:

                    break;
            }
        }
    };

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.iv_authors_icon_news_details:
            case R.id.tv_authors_name_news_details:

                break;
            case R.id.iv_stand_news_details:
            case R.id.iv_down_news_details:
            case R.id.iv_up_news_details:
            case R.id.tv_autograph_news_details:
                if (popup.isShowing()) {
                    iv_up.setVisibility(View.INVISIBLE);
                    iv_down.setVisibility(View.VISIBLE);
                    popup.dismiss();
                    rel_bg.setVisibility(View.INVISIBLE);
                } else {
                    iv_up.setVisibility(View.VISIBLE);
                    iv_down.setVisibility(View.INVISIBLE);
                    showPopupWindow();
                    popup.showAtLocation(v, Gravity.CENTER_VERTICAL, 0, -63);
                    rel_bg.setVisibility(View.VISIBLE);
                }

                break;
            case R.id.iv_news_details_back:
                finish();
                break;
            case R.id.iv_news_details_comments:
                Intent intent = new Intent(this, WriteArticleActivity.class);
                startActivity(intent);
                break;
            case R.id.iv_news_details_favorite:
                if (iv_favorite.isChecked()) {
                    Toast.makeText(this, "赞+1", Toast.LENGTH_SHORT).show();
                }
                if (!iv_favorite.isChecked()) {
                    Toast.makeText(this, "取消赞", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.iv_news_details_share:
                showShare();
                break;
        }
    }

    private void showPopupWindow() {
        popup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        ColorDrawable dw = new ColorDrawable(0xb0000000);
//        设置SelectPicPopupWindow弹出窗体的背景
        popup.setBackgroundDrawable(dw);
//        popup.setOutsideTouchable(true);
        popup.setFocusable(false);


    }

    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);

    }

    @Override
    public void onItemClick(int position) {
        Intent intent = new Intent(AllNewsDetailsActivity.this, AllNewsDetailsActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("详情", String.valueOf(user.getData().getLatestArticle().get(position).getPostId()));
        intent.putExtras(bundle);
        startActivity(intent);
    }
    private void showShare() {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间等使用
        oks.setTitle("标题");
        // titleUrl是标题的网络链接，QQ和QQ空间等使用
        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("我是分享文本");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");

        // 启动分享GUI
        oks.show(this);
    }
}